<?php

declare(strict_types=1);

namespace App\Services;

use Hyperf\Di\Annotation\Inject;
use App\Exception\ApiException;
use App\Constants\ErrorCode;

class FileUploadService extends BaseService
{

    public function index(array $params)
    {
        $file = $params['file'];
        if (!$file->isValid()) {
            throw new ApiException(ErrorCode::ERROR, "无效文件");
        }
        $extension = $file->getExtension();     //扩展名
        if(!in_array($extension, ['jpg','jpeg','png','gif','xls','xlsx','csv']))
        {
            throw new ApiException(ErrorCode::ERROR, "仅支持图片，EXCEL常用格式文件");
        }
        $year = date('Y');
        $month = date('m');
        $relativePath = '/public/upload/'.$year.'/'.$month.'/';       //相对路径
        $filePath = BASE_PATH . $relativePath;        //存储路径
        if(!is_dir($filePath))
        {
            mkdir($filePath, 0777, true);
        }
        $fileName = get_rand_str();     //文件名
        $fullPath = $filePath.$fileName.'.'.$extension;     //完整文件路径
        $file->moveTo($fullPath);
        if (!$file->isMoved()) {
            throw new ApiException(ErrorCode::ERROR, "文件上传失败");
        }

        $filePath = env('HTTP_HOST').$relativePath.$fileName.'.'.$extension;

        return ['file_url'=>$filePath];
    }

}